﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace rFDevLib {
    public class TGMGraphic {
        // Parameters for external use
        public int xRes = 250, yRes = 250; // Bitmap resolution
        public double margin = 0.09; // Margin around outside to remain blank, like a border

        // Members for internal use
        private double scale = 0.0001; // Meters / Pixel
        private double cX = 0.0, cY = 0.0; // Center spacial coordinate

        private int mX = 125, mY = 125; // Center coordinate of the bitmap

        private Bitmap bmp;
        private Graphics gfx;

        public void NewGraphic( TGMDimensions specs ) {
            bmp = new Bitmap( xRes, yRes );
            gfx = Graphics.FromImage( bmp );

            gfx.SmoothingMode = SmoothingMode.HighSpeed;

            double  tireRadius = specs.sidewallHeight + Math.Max( specs.ringBulge, 0.0 ),
                    tireWidth = Math.Max( specs.rimWidth, specs.treadWidth );

            scale = (double)Math.Min(xRes, yRes) / Math.Max( tireRadius + margin, tireWidth + margin );

            cX = 0.0;
            cY = -specs.rimRadius - (specs.sidewallHeight * 0.5);

            mX = xRes / 2;
            mY = yRes / 2;
        }

        public void AddNode( Node n ) {
            int x, y;

            double dx = (n.x - cX) * scale, dy = (-n.y + cY) * scale;


            x = mX + (int)Math.Round( dx );
            y = mY + (int)Math.Round( dy );

            Color green = Color.FromArgb( 0, 0xFF, 0 );
            Brush greenBrush = new SolidBrush( green );
            gfx.FillEllipse( greenBrush, x - 2, y - 2, 4.0f, 4.0f );
        }

        public Bitmap GetBmp() {
            return bmp;
        }

        public System.Windows.Media.Imaging.BitmapSource GetBmpSrc() {
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                  bmp.GetHbitmap(),
                  IntPtr.Zero,
                  System.Windows.Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions() );
        }
    }
}
